<template>
  <v-container>
    <v-dialog width="400" v-model="successmessage" persistent>
      <v-toolbar dark color="primary">
        <v-toolbar-title>{{$t("message.success")}}</v-toolbar-title>
      </v-toolbar>
      <div class="text-center pa-5">
        <v-btn fab large color="primary" @click="successmessage=false">
          <v-icon>mdi-check</v-icon>
        </v-btn>
      </div>
    </v-dialog>
    <v-dialog v-model="uploadvideo" :fullscreen="$vuetify.breakpoint.xsOnly">
      <v-dialog width="200" v-model="uploading" persistent>
        <v-toolbar dark color="primary">
          <v-toolbar-title>{{$t("message.uploading")}}({{nownumber}}/{{totalnumber}})</v-toolbar-title>
        </v-toolbar>

        <div class="text-center pa-5">
          <v-progress-circular
            :rotate="-90"
            :size="100"
            :width="15"
            :value="process"
            color="primary"
          >{{ process }}</v-progress-circular>
        </div>
      </v-dialog>
      <v-card>
        <v-toolbar dark color="primary">
          <v-btn icon dark @click="uploadvideo=false">
            <v-icon>mdi-close</v-icon>
          </v-btn>
          <v-toolbar-title>{{$t("message.uploadnew")}}</v-toolbar-title>
        </v-toolbar>
        <v-container>
          <v-row>
            <v-col cols="4">
              <v-row>
                <v-col cols="12">
                  <div class="cropper2 ml-3">
                    <vueCropper
                      ref="cropper2"
                      :img="option.img"
                      :outputSize="option.size"
                      :outputType="option.outputType"
                      :info="false"
                      :fixed="true"
                      :fixedNumber="[4,3]"
                      :full="option.full"
                      :centerBox="true"
                      :canMove="option.canMove"
                      :canMoveBox="option.canMoveBox"
                      :original="option.original"
                      :autoCrop="option.autoCrop"
                      :fixedBox="option.fixedBox"
                      @realTime="realTime"
                    ></vueCropper>
                  </div>
                </v-col>
                <v-col cols="12">
                  <v-file-input
                    outlined
                    rounded
                    v-model="avatarupfile"
                    :rules="updaterules"
                    type="file"
                    :label="this.$t('message.uploadgroupimg')"
                    prepend-icon="mdi-image"
                    accept="image/png, image/jpeg, image/gif, image/jpg"
                    class="ml-4"
                    @change="uploadImg($event)"
                  >
                    <template v-slot:selection="{ text }">
                      <v-chip small label color="primary">{{ text }}</v-chip>
                    </template>
                  </v-file-input>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="8">
              <v-row>
                <v-col cols="12">
                  <v-text-field
                    rounded
                    prepend-icon="mdi-book-variant"
                    v-model="Gname"
                    label="课程名"
                    color="primary"
                    required
                    outlined
                  ></v-text-field>
                </v-col>
                <v-col cols="12">
                  <v-textarea
                    rounded
                    prepend-icon="mdi-information-variant"
                    v-model="Gtext"
                    label="简介"
                    color="primary"
                    required
                    outlined
                  ></v-textarea>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12">
              <div class="title">
                {{$t("message.grouptags")}}
                <div class="caption">{{$t("message.tagshelp")}}</div>
              </div>
              <v-chip-group v-model="tagselected" multiple column active-class="primary--text">
                <v-chip filter v-for="tag in tags" :key="tag">{{ tag }}</v-chip>
              </v-chip-group>
            </v-col>
            <v-col cols="12">
              <v-file-input
                outlined
                rounded
                v-model="uploadvideos"
                type="file"
                :label="this.$t('message.uploadvideos')"
                prepend-icon="mdi-video"
                accept="video/mp4, video/avi, video/mov"
                class="ml-4"
                show-size
                counter
                multiple
                @change="uploadVideoCheck($event)"
              >
                <template v-slot:selection="{ text }">
                  <v-chip small label color="primary">{{ text }}</v-chip>
                </template>
              </v-file-input>
            </v-col>

            <v-col cols="12">
              <v-row>
                <v-col cols="11" class="ma-0">
                  <v-card flat height="200" class="text-center display-1 ma-2 pa-5">
                    <v-card-text class="title">{{$t("message.price")}}</v-card-text>
                    <p class="display-3">{{price}}{{$t("message.points")}}</p>
                  </v-card>
                </v-col>
                <v-col cols="1">
                  <v-slider v-model="price" vertical max="200"></v-slider>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12">
              <div class="text-center">
                <v-btn color="primary" fab x-large @click="finish">
                  <v-icon>mdi-check</v-icon>
                </v-btn>
              </div>
            </v-col>
          </v-row>
        </v-container>
      </v-card>
    </v-dialog>
    <v-card class="text-center pa-10" v-if="userinfo.type==0">
      <h1 class="display-3">{{$t("message.notteacher")}}</h1>
      <br />
      <v-icon size="140">mdi-emoticon-sad</v-icon>
      <br />
      <br />

      <h2 class="display-1">{{$t("message.askadmin")}}</h2>
    </v-card>
    <v-card v-else class="text-center pa-5">
      <v-row>
        <v-col cols="12">
          <div>
            <v-row>
              <v-col cols="6">
                <v-hover v-slot:default="{ hover }">
                  <v-card :elevation="hover ? 15 : 1" class="text-center pa-3">
                    <v-card-title>{{$t("message.totalplayed")}}</v-card-title>
                    <v-badge color="primary">
                      <template v-if="value[7]!=0" v-slot:badge>{{value[7]}}</template>
                      <p class="display-1">{{totalplayed}}</p>
                    </v-badge>

                    <br />
                  </v-card>
                </v-hover>
              </v-col>
              <v-col cols="6">
                <v-hover v-slot:default="{ hover }">
                  <v-card :elevation="hover ? 15 : 1" class="text-center pa-3">
                    <v-card-title>{{$t("message.totalfavored")}}</v-card-title>
                    <v-badge color="primary">
                      <template v-if="value1[7]!=0" v-slot:badge>{{value1[7]}}</template>
                      <p class="display-1">{{totalfavored}}</p>
                    </v-badge>
                    <br />
                  </v-card>
                </v-hover>
              </v-col>
            </v-row>
            <v-row>
              <v-col cols="6">
                <v-hover v-slot:default="{ hover }">
                  <v-card :elevation="hover ? 15 : 1" class="text-center pa-3">
                    <v-card-title>{{$t("message.totaluploaded")}}</v-card-title>
                    <p class="display-1">{{uploadnumber}}</p>
                    <br />
                  </v-card>
                </v-hover>
              </v-col>
              <v-col cols="6">
                <v-hover v-slot:default="{ hover }">
                  <v-card :elevation="hover ? 15 : 1" class="text-center pa-3">
                    <v-btn
                      elevation="15"
                      absolute
                      bottom
                      right
                      color="primary"
                      x-large
                      fab
                      @click="uploadvideo=true"
                    >
                      <v-icon>mdi-plus</v-icon>
                    </v-btn>
                    <v-card-title>{{$t("message.totalfan")}}</v-card-title>
                    <p class="display-1">{{fannumber}}</p>
                    <br />
                  </v-card>
                </v-hover>
              </v-col>
            </v-row>
          </div>
        </v-col>
      </v-row>
      <v-row>
        <v-col cols="12">
          <p class="display-1">{{$t("message.sevenplayed")}}</p>
          <v-lazy
            v-model="isActive"
            :options="{
          threshold: .5
        }"
            transition="fade-transition"
          >
            <v-sparkline
              fill
              padding="5"
              auto-draw
              smooth="15"
              :value="value"
              :gradient="gradient1"
              type="trend"
              showLabels
            ></v-sparkline>
          </v-lazy>
        </v-col>

        <v-col cols="12">
          <p class="display-1">{{$t("message.sevenfavored")}}</p>
          <v-lazy
            v-model="isActive2"
            :options="{
          threshold: .5
        }"
            transition="fade-transition"
          >
            <v-sparkline
              fill
              padding="5"
              auto-draw
              smooth="15"
              :value="value1"
              :gradient="gradient2"
              type="trend"
              showLabels
            ></v-sparkline>
          </v-lazy>
        </v-col>
      </v-row>
    </v-card>
  </v-container>
</template>

<script>
const gradients = [
  ["#222"],
  ["#42b3f4"],
  ["red", "orange", "yellow"],
  ["purple", "violet"],
  ["#00c6ff", "#F0F", "#FF0"],
  ["#f72047", "#ffd200", "#1feaea"]
];
export default {
  data: () => ({
    nownumber: 0,
    totalnumber: 0,
    successmessage: false,
    process: 0,
    uploading: false,
    getgid: null,
    price: 0,
    Gname: null,
    Gtext: null,
    uploadvideos: [],
    tagselected: [],
    tags: [
      "中医学",
      "医学影像学",
      "生物化学",
      "药理学",
      "微生物学",
      "医学免疫学",
      "空间医学",
      "舌诊",
      "中西医结合",
      "儿科",
      "方剂学",
      "智能中医",
      "妇产科",
      "胎儿医学",
      "超声",
      "骨骼",
      "病理生理学",
      "口腔医学",
      "药膳",
      "护理学",
      "解剖学",
      "针灸",
      "推拿",
      "诊断学",
      "康复医学",
      "生理学",
      "血液学",
      "预防医学",
      "经脉医学",
      "医学养生",
      "脊骨神经医学",
      "基础医学"
    ],
    img: null,
    updaterules: [
      value => !value || value.size < 5000000 || "Must less then 5Mb"
    ],
    edittextinput: "",
    edittext: false,
    message: "",
    uploadsucceed: false,
    isuploading: false,
    messagedialog: false,
    avatarupfile: [],
    avatardialog: false,
    readonly: true,
    userinfo: "",
    headImg: "",
    //剪切图片上传
    crap: false,
    previews: {},
    option: {
      img: "",
      outputSize: 1, //剪切后的图片质量（0.1-1）
      full: false, //输出原图比例截图 props名full
      outputType: "png",
      canMove: true,
      original: false,
      canMoveBox: false,
      autoCrop: true,
      fixedBox: true
    },
    fileName: "", //本机文件地址
    downImg: "#",
    uploadImgRelaPath: "", //上传后的图片的地址（不带服务器域名）
    totalfavored: null,
    totalplayed: null,
    uploadvideo: false,
    userinfo: null,
    uploadnumber: null,
    fannumber: null,
    gradient1: gradients[5],
    gradient2: gradients[4],
    value: [],
    value1: [],
    isActive: false,
    isActive2: false
  }),
  methods: {
    Jsonfy() {
      var arrays = new Array();
      for (var i = 0; i < this.tagselected.length; i++) {
        arrays.push(this.tags[this.tagselected[i]]);
      }
      var output = JSON.stringify(arrays);
      console.log(output);
      return output;
    },
    init() {
      if (this.$cookies.isKey("user")) {
        var loginBean = new URLSearchParams();
        loginBean.append(
          "fetchUserBean.uid",
          String(this.$cookies.get("user"))
        ); //你要传给后台的参数值 key/value
        this.$axios({
          method: "post",
          url: "http://47.100.137.177:8080/YimooBP1.0/myfetchuser",
          data: loginBean
        })
          .then(response => {
            this.userinfo = JSON.parse(response.data);
            this.uploadnumberinit();
            this.fannumberinit();
            this.sevenfavoredinit();
            this.sevenplayedinit();
            this.totalplayedinit();
            this.totalfavoredinit();
          })
          .catch(function(error) {
            console.log(error);
          });
      }
    },
    totalplayedinit() {
      var params = new URLSearchParams();
      params.append("uid", Number(this.userinfo.uid));
      this.$axios({
        method: "post",
        url: "http://47.100.35.226/php/sumplayed.php",
        data: params
      })
        .then(response => {
          this.totalplayed = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    totalfavoredinit() {
      var params = new URLSearchParams();
      params.append("uid", Number(this.userinfo.uid));
      this.$axios({
        method: "post",
        url: "http://47.100.35.226/php/sumfavor.php",
        data: params
      })
        .then(response => {
          this.totalfavored = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    sevenplayedinit() {
      var params = new URLSearchParams();
      params.append("uid", Number(this.userinfo.uid));
      this.$axios({
        method: "post",
        url: "http://47.100.35.226/php/7dplayed.php",
        data: params
      })
        .then(response => {
          this.value = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    sevenfavoredinit() {
      var params = new URLSearchParams();
      params.append("uid", Number(this.userinfo.uid));
      this.$axios({
        method: "post",
        url: "http://47.100.35.226/php/7dfavor.php",
        data: params
      })
        .then(response => {
          this.value1 = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    uploadnumberinit() {
      var params = new URLSearchParams();
      params.append("uid", Number(this.userinfo.uid));
      this.$axios({
        method: "post",
        url: "http://47.100.35.226/php/uploadnumber.php",
        data: params
      })
        .then(response => {
          this.uploadnumber = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    fannumberinit() {
      var params = new URLSearchParams();
      params.append("uid", Number(this.userinfo.uid));
      this.$axios({
        method: "post",
        url: "http://47.100.35.226/php/befocusednumber.php",
        data: params
      })
        .then(response => {
          this.fannumber = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    creategroup() {
      let _this = this;
      let formData = new FormData();
      this.$refs.cropper2.getCropBlob(data => {
        let img = window.URL.createObjectURL(data);

        formData.append("createGroupBean.file", data);
        formData.append("createGroupBean.uid", this.userinfo.uid);
        formData.append("createGroupBean.fileName", this.Gname + ".jpg");
        formData.append("createGroupBean.name", this.Gname);
        formData.append("createGroupBean.text", this.Gtext);
        formData.append("createGroupBean.tag", this.Jsonfy());
        formData.append("createGroupBean.price", this.price);
        console.log(formData);
        this.$axios({
          method: "post",
          url: "/api/YimooBP1.0/mycreategroup",
          data: formData
        })
          .then(
            response => {
              console.log(response.data);
              this.getgid = response.data;

              this.nownumber = 1;
              this.totalnumber = this.uploadvideos.length;
              this.onupvideos(
                this.uploadvideos[this.nownumber - 1],
                this.uploadvideos[this.nownumber - 1].name,
                this.getgid
              );
            }

            //this.$route.meta.title=this.userinfo.name;
          )
          .catch(function(error) {
            console.log(error);
          });
      });
    },
    async onupvideos(file, title, gid) {
      let _this = this;
      let formData = new FormData();
      formData.append("uploadVideoBean.file", file);
      formData.append("uploadVideoBean.title", title);
      formData.append("uploadVideoBean.gid", gid);
      formData.append("uploadVideoBean.fileName", gid + "T" + title + ".mp4");
      console.log(formData);
      await this.$axios({
        method: "post",
        url: "/api/YimooBP1.0/myuploadvideo",
        data: formData,
        onUploadProgress: function(progressEvent) {
          let complete =
            ((progressEvent.loaded / progressEvent.total) * 100) | 0;
          console.log("上传 " + complete);
          _this.process = Number(complete);
          console.log(_this.process);
        }
      })
        .then(response => {
          console.log(response.data);

          if (this.nownumber >= this.totalnumber) {
            this.dialogreturn();
            return;
          } else {
            this.nownumber = this.nownumber + 1;
            this.onupvideos(
              this.uploadvideos[this.nownumber - 1],
              this.uploadvideos[this.nownumber - 1].name,
              this.getgid
            );
          }
          // return response.data;
          //this.$route.meta.title=this.userinfo.name;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    dialogreturn() {
      this.uploading = false;
      this.successmessage = true;
      this.uploadvideo = false;
    },
    finish() {
      this.uploading = true;
      this.creategroup();
    },
    // 实时预览函数
    realTime(data) {
      console.log(data);
      this.previews = data;
    },

    //选择本地图片
    uploadImg(e) {
      console.log("success");
      var _this = this;
      //上传图片
      var file = this.avatarupfile;
      _this.fileName = file.name;
      if (
        !/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(this.avatarupfile.name)
      ) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        _this.avatarupfile = [];
        return false;
      }
      var reader = new FileReader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        _this.option.img = data;
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(file);
    },
    uploadVideoCheck(e) {
      var _this = this;
      //上传视频
      for (var i = 0; i < _this.uploadvideos.length; i++) {
        var file = this.uploadvideos[i];

        console.log(_this.uploadvideos.length);
        console.log(_this.uploadvideos[i].name);
        if (!/\.(mp4|mov|avi)$/.test(this.uploadvideos[i].name)) {
          alert("视频类型必须是.mp4.mov.avi中的一种");
          _this.avatarupfile = [];
          return false;
        }
      }
    }
  },
  computed: {},
  watch: {
    tagselected: function() {
      console.log(this.tagselected);
    }
  },
  created() {
    this.init();
  }
};
</script>

<style lang="scss" scoped>
//改变背景色
.cropper-box {
  background: #333 !important;
}
//使截图框变为圆形
.cropper-crop-box {
  overflow: hidden;
  border-radius: 0% !important;
}
//截图相关样式

.cropper2 {
  width: 200px;
  height: 150px;
  position: relative;
}
.show-preview {
  flex: 1;
  -webkit-flex: 1;
  display: flex;
  display: -webkit-flex;
  justify-content: center;
  -webkit-justify-content: center;
  .preview {
    overflow: hidden;
    border-radius: 50%;
    border: 1px solid #cccccc;
    background: #cccccc;
    margin-left: 40px;
  }
}
</style>